<template>
  <div class="p-6">
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-800">案例管理</h1>
      <p class="text-gray-500 mt-1">管理网站的所有案例</p>
    </div>

    <!-- 操作栏 -->
    <div class="bg-white p-4 rounded-lg shadow-sm mb-6">
      <div class="flex flex-wrap justify-between items-center gap-4">
        <div class="flex items-center gap-2">
          <input 
            type="text" 
            v-model="searchKeyword" 
            placeholder="搜索案例名称" 
            class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
          <button 
            @click="handleSearch" 
            class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
          >
            搜索
          </button>
        </div>
        <button 
          @click="handleAddCase" 
          class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors"
        >
          <i class="fa fa-plus mr-1"></i> 添加案例
        </button>
      </div>
    </div>

    <!-- 案例列表 -->
    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="bg-gray-50 border-b border-gray-200">
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">案例名称</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">所属分类</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="item in caseList" :key="item.id">
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ item.id }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ item.title }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ item.categoryName || '未分类' }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ formatDate(item.createdAt) }}</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800" v-if="item.status === 1">
                  已发布
                </span>
                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800" v-else>
                  草稿
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button 
                  @click="handleEditCase(item.id)" 
                  class="text-blue-600 hover:text-blue-900 mr-3"
                >
                  <i class="fa fa-pencil mr-1"></i> 编辑
                </button>
                <button 
                  @click="handleDeleteCase(item.id)" 
                  class="text-red-600 hover:text-red-900"
                >
                  <i class="fa fa-trash mr-1"></i> 删除
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 无数据状态 -->
      <div v-if="caseList.length === 0" class="px-6 py-12 text-center text-gray-500">
        暂无案例数据
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="caseList.length > 0" class="mt-6 flex justify-between items-center">
      <div class="text-sm text-gray-500">
        共 {{ totalCount }} 条数据，每页显示 {{ pageSize }} 条
      </div>
      <div class="flex items-center space-x-2">
        <button 
          @click="changePage(currentPage - 1)" 
          :disabled="currentPage === 1" 
          class="px-3 py-1 border border-gray-300 rounded text-sm hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          上一页
        </button>
        <button 
          v-for="page in pageRange" 
          :key="page" 
          @click="changePage(page)" 
          :class="[currentPage === page ? 'bg-blue-600 text-white' : 'bg-white text-gray-700', 'px-3 py-1 border rounded text-sm hover:bg-gray-50']"
        >
          {{ page }}
        </button>
        <button 
          @click="changePage(currentPage + 1)" 
          :disabled="currentPage === totalPages" 
          class="px-3 py-1 border border-gray-300 rounded text-sm hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 添加/编辑案例弹窗 -->
    <CaseEditDialog 
      ref="caseEditDialog" 
      :case-id="editCaseId" 
      @refresh="fetchCaseList"
    />

    <!-- 确认删除弹窗 -->
    <ConfirmDialog 
      ref="confirmDialog" 
      title="确认删除"
      content="确定要删除这个案例吗？此操作不可撤销。"
      @confirm="confirmDelete"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCaseList, deleteCase } from '@/api/case'
import { formatDate } from '@/utils/date'
import { showToast } from '@/utils/toast'
import CaseEditDialog from './components/CaseEditDialog.vue'
import ConfirmDialog from '@/components/ConfirmDialog.vue'

const router = useRouter()
const caseEditDialog = ref(null)
const confirmDialog = ref(null)

// 数据
const caseList = ref([])
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')
const editCaseId = ref(null)
const deleteCaseId = ref(null)

// 计算属性
const totalPages = computed(() => Math.ceil(totalCount.value / pageSize.value))
const pageRange = computed(() => {
  const range = []
  const maxPageButtons = 5
  let startPage = Math.max(1, currentPage.value - Math.floor(maxPageButtons / 2))
  let endPage = Math.min(totalPages.value, startPage + maxPageButtons - 1)
  
  if (endPage - startPage + 1 < maxPageButtons) {
    startPage = Math.max(1, endPage - maxPageButtons + 1)
  }
  
  for (let i = startPage; i <= endPage; i++) {
    range.push(i)
  }
  return range
})

// 获取案例列表
const fetchCaseList = async () => {
  try {
    const response = await getCaseList({
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    })
    caseList.value = response.list || []
    totalCount.value = response.total || 0
  } catch (error) {
    showToast('获取案例列表失败', 'error')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchCaseList()
}

// 切换页码
const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return
  currentPage.value = page
  fetchCaseList()
}

// 添加案例
const handleAddCase = () => {
  editCaseId.value = null
  caseEditDialog.value.open()
}

// 编辑案例
const handleEditCase = (id) => {
  editCaseId.value = id
  caseEditDialog.value.open()
}

// 删除案例
const handleDeleteCase = (id) => {
  deleteCaseId.value = id
  confirmDialog.value.open()
}

// 确认删除
const confirmDelete = async () => {
  try {
    await deleteCase(deleteCaseId.value)
    showToast('删除成功')
    fetchCaseList()
  } catch (error) {
    showToast('删除失败', 'error')
  }
}

// 初始化
onMounted(() => {
  fetchCaseList()
})
</script>

<style scoped>
/* 自定义样式 */
</style>